const express = require("express");
const app = express();

const fs = require("fs");
const path = require("path");
var ejs = require("ejs");
app.use(express.static(path.join(__dirname, "/public")));
app.set("view engine", "ejs");
const moment = require("moment");

const configPath = path.join(process.execPath, "../", "./config.json");
let isConfigExist = fs.existsSync(configPath);

let exeConfig = null;
if (isConfigExist) {
  exeConfig = JSON.parse(fs.readFileSync(configPath, "utf8"));
} else {
  exeConfig = {
    root_dir: "/Users/liuyang/Desktop/STEP_TMP/step-share",
    port: 3601,
  };
}

const share_root_dir = exeConfig.root_dir.replace(/\\/g, "/");

const port = exeConfig.port | 3600;

app.all("*", (req, res) => {
  console.log("url:" + req.url);
  console.log(decodeURI(req.url));
  if (decodeURI(req.url) == "/favicon.ico") {
    return;
  }
  const current_path = decodeURI(req.url);
  const full_path = share_root_dir + current_path;
  console.log("全路径：" + full_path);
  const is_dir = fs.statSync(full_path).isDirectory();
  if (is_dir) {
    console.log("文件夹");
    const result = getAllFiles(full_path);
    res.render(path.join(__dirname, "/views/index.ejs"), {
      result: result,
      root_dir: share_root_dir.replace(/\//g, "\\"),
      current_path: current_path,
    });
  } else {
    console.log("文件：" + full_path);
    res.sendFile(full_path);
  }
});

function getAllFiles(root_dir) {
  let files = [];
  fs.readdirSync(root_dir).forEach((name) => {
    if (name !== ".DS_Store") {
      const filePath = path.join(root_dir, name);
      console.log("path:" + filePath);
      const stat = fs.statSync(filePath);
      if (stat.birthtime) {
        stat.birthtime = moment(stat.birthtime).format("YYYY-MM-DD HH:ss");
      }
      if (stat.mtime) {
        stat.mtime = moment(stat.mtime).format("YYYY-MM-DD HH:ss");
      }
      if (stat.size) {
        if (1024 * 1024 < parseInt(stat.size)) {
          stat.size = `${(
            Math.floor(parseInt(stat.size)) /
            (1024 * 1024)
          ).toFixed(2)} MB`;
        } else if (parseInt(stat.size) < 1024) {
          stat.size = `${stat.size} B`;
        } else if (1024 < parseInt(stat.size) < 1024 * 1024) {
          stat.size = `${(Math.floor(parseInt(stat.size)) / 1024).toFixed(
            2
          )} KB`;
        }
      }
      let sort = "other";
      let sort_urls = {
        dir:
          "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.51yuansu.com%2Fpic2%2Fcover%2F00%2F33%2F67%2F58112c30514ba_610.jpg&refer=http%3A%2F%2Fpic.51yuansu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621066756&t=1e4961a0fae646d64d8579760a1c6943",
        exe:
          "https://img1.baidu.com/it/u=3078115390,1520230774&fm=26&fmt=auto&gp=0.jpg",
        file:
          "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F00%2F27%2F84%2F3056d190c8efe1b.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621068534&t=ecdba7e91fc20100027b1f073e65cd9e",
        rar:
          "https://img0.baidu.com/it/u=729654212,3399793282&fm=26&fmt=auto&gp=0.jpg",
        xlsx:
          "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fku.90sjimg.com%2Felement_origin_min_pic%2F01%2F00%2F13%2F0556f39de1839fc.jpg&refer=http%3A%2F%2Fku.90sjimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621482460&t=a34a19fbc37d761fc682d54e4cc01009",
        ppt:
          "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F8760074a30712ff73496d293b410711480c6a85663c6-KDJ0uC_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621482431&t=ec0660d7b6b760733b75ca72b28de4f8",
        zip:
          "https://image.baidu.com/search/detail?ct=503316480&z=&tn=baiduimagedetail&ipn=d&word=rar%20icon&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=-1&hd=&latest=&copyright=&cs=2819882906,3380918387&os=280594849,4155512230&simid=4254161677,701982114&pn=7&rn=1&di=139590&ln=1461&fr=&fmq=1618890367021_R&ic=&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&is=0,0&istype=2&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&hs=2&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fbpic.588ku.com%252Felement_origin_min_pic%252F17%252F08%252F31%252Faed5d06d8fac9a9ffa5bf7b05b8eb0ee.jpg%2521%252Ffwfh%252F804x680%252Fquality%252F90%252Funsharp%252Ftrue%252Fcompress%252Ftrue%26refer%3Dhttp%253A%252F%252Fbpic.588ku.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1621482367%26t%3Ddd08ca36f08799d687d1a2a8ca5e1108&rpstart=0&rpnum=0&adpicid=0&force=undefined",
        pdf:
          "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F00%2F16%2F03%2F7956aed15300f1a.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621482616&t=b992038cd4591772e8cbf2c845475666",
        mp4:
          "https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/baike/pic/item/a6efce1b9d16fdfad0cff504be8f8c5495ee7bbc.jpg",
        dll:
          "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F00%2F22%2F09%2F6056ce71973d34c.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621483221&t=d2db1e7ba6d925e0c159eef58617619c",
        txt:
          "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fku.90sjimg.com%2Felement_origin_min_pic%2F00%2F43%2F05%2F5256d69b6b249c9.jpg&refer=http%3A%2F%2Fku.90sjimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621483241&t=4a97d84dcb0aa1b0eef11782183f6e1d",
        docx:
          "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F01%2F03%2F85%2F7556f45e2658b18.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621486101&t=6c368d22e4c1a5538c8a205b591efb8f",
        jpg:
          "https://img1.baidu.com/it/u=1457654414,2553274649&fm=26&fmt=auto&gp=0.jpg",
      };
      let icon = sort_urls.file;
      if (
        name.endsWith(".jpg") ||
        name.endsWith(".png") ||
        name.endsWith(".gif") ||
        name.endsWith(".JPEG")
      ) {
        sort = "jpg";
        icon = sort_urls.jpg;
      }
      if (name.endsWith(".docx") || name.endsWith(".doc")) {
        sort = "docx";
        icon = sort_urls.docx;
      }
      if (name.endsWith(".dll")) {
        sort = "dll";
        icon = sort_urls.dll;
      }
      if (name.endsWith(".txt")) {
        sort = "txt";
        icon = sort_urls.txt;
      }
      if (name.endsWith(".exe")) {
        sort = "exe";
        icon = sort_urls.exe;
      }
      if (name.endsWith(".rar")) {
        sort = "rar";
        icon = sort_urls.rar;
      }
      if (name.endsWith(".xlsx")) {
        sort = "xlsx";
        icon = sort_urls.xlsx;
      }
      if (name.endsWith(".ppt")) {
        sort = "ppt";
        icon = sort_urls.ppt;
      }
      if (name.endsWith(".zip")) {
        sort = "zip";
        icon = sort_urls.zip;
      }
      if (name.endsWith(".pdf")) {
        sort = "pdf";
        icon = sort_urls.pdf;
      }
      if (name.endsWith(".mp4")) {
        sort = "mp4";
        icon = sort_urls.mp4;
      }

      files.push({
        ...stat,
        parentpath: root_dir,
        path: filePath,
        filename: name,
        type: stat.isFile() ? "file" : "dir",
        sort: sort,
        icon: stat.isFile() ? icon : sort_urls.dir,
      });
    }
  });
  return files;
}
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});
